# 数据库封装
import pymysql


class DBUtil:
    # 定义全局变量
    conn = None

    # 建立连接
    @classmethod
    def __connect_db(cls):
        cls.conn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2021",
                                   database="ihrm", charset="utf8")
        return cls.conn

    # 关闭连接
    @classmethod
    def __close_db(cls):
        cls.conn.close()

    # 查询语句
    @classmethod
    def search(cls, sql):
        cursor = None
        try:
            # 建立连接
            cls.conn = cls.__connect_db()
            # 创建cursor
            cursor = cls.conn.cursor()
            # 执行SQL语句
            cursor.execute(sql)
            result = cursor.fetchone()
            # 提交事务
            cls.conn.commit()
            return result
        except Exception as error:
            print("查询错误信息：", str(error))
            # 回滚事务
            cls.conn.rollback()
        finally:
            cursor.close()
            cls.__close_db()

    # 增删改语句
    @classmethod
    def uid_db(cls, sql):
        cursor = None
        affected_rows = None
        try:
            # 建立连接
            cls.conn = cls.__connect_db()
            # 创建cursor
            cursor = cls.conn.cursor()
            # 执行SQL语句
            cursor.execute(sql)
            # 提交事务
            cls.conn.commit()
            # 获取影响行数
            affected_rows = cls.conn.affected_rows()
        except Exception as error:
            print("错误语句：", str(error))
            # 回滚事务
            cls.conn.rollback()
        finally:
            cursor.close()
            cls.__close_db()
            return affected_rows


if __name__ == '__main__':
    # print(DBUtil.search("select * from bs_user where id = 1"))
    print(DBUtil.uid_db("DELETE from bs_user where mobile = '13892133563';"))